package com.portal.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 短信发送工具类
 */
@Slf4j
@Component
public class SmsUtil {

    @Value("${sms.signature}")
    private String signature;

    @Value("${sms.template-code}")
    private String templateCode;

    @Value("${sms.accessKey}")
    private String accessKey;

    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 发送短信
     * @param phoneNumbers 手机号
     * @param code         验证码
     * @return 返回响应码
     */
    public String sendSms(String phoneNumbers, String code) {
        //这里需要修改发送短信的ID和密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", 
                                                           accessKey, 
                                                           accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSysRegionId("cn-hangzhou");
        request.setPhoneNumbers(phoneNumbers);
        request.setSignName(signature);
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            log.info("\n请求ID:" + response.getRequestId() + "\n业务ID：" + response.getBizId()
                    + "\n响应码：" + response.getCode() + "\n响应消息：" + response.getMessage());
            return response.getCode();
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }
}